/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package my12306.http;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import my12306.db.SQLite;
import org.json.JSONArray;
import org.json.JSONException;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jack
 */
public class Utils {

    private final static org.slf4j.Logger log = LoggerFactory.getLogger(SQLite.class);

    public static String extractInfo(String raw, String replacement) {
        return extractInfo(raw, "'>", replacement);
    }

    public static String extractInfo(String raw, String split, String replacement) {
        try {
            return raw.split(split)[1].replace(replacement, "");
        } catch (ArrayIndexOutOfBoundsException aioobe) {
        }
        return raw;
    }

    /**
     * extract train no from raw data
     *
     * items[1] "<span id='id_6c0000G54802' class='base_txtdiv'
     * onmouseover=javascript:onStopHover('6c0000G54802#IZQ#LBN')
     * onmouseout='onStopOut()'>G548</span>"
     *
     * @param raw
     * @return
     */
    public static String extractTrainNo(String raw) {
        String result = "";
        try {
            String pattern = "onStopHover\\('([\\w]{12,})#";
            Matcher matcher = Pattern.compile(pattern).matcher(raw);
            if (matcher.find()) {
                result = matcher.group(1);
            }
        } catch (Exception ex) {
        }
        return result;
    }

    /**
     * 从<a></a>中提取 链接内容
     *
     * @param raw <a class='btn130' style='text-decoration:none;'>链接内容</a>
     * @return 链接内容
     */
    public static String extractButtonInfo(String raw) {
        String result = "";
        try {
            String pattern = "([^a-z&&[^;'>]]+)(?=</a>)";
            Matcher matcher = Pattern.compile(pattern).matcher(raw);
            if (matcher.find()) {
                result = matcher.group(1);
            }
        } catch (Exception ex) {
        }
        return result;
    }

    /**
     * 提取始、终站的图片信息。
     *
     * @param raw <img src='/otsweb/images/tips/last.gif'>广州南<br>13:39 <img
     * src='/otsweb/images/tips/first.gif'>郑州<br>08:00
     * @return last.gif
     */
    public static String extractImageInfo(String raw) {
        String result = "";
        try {
            String pattern = "([\\w]+.gif)";
            Matcher matcher = Pattern.compile(pattern).matcher(raw);
            if (matcher.find()) {
                result = matcher.group(1);
            }
        } catch (Exception ex) {
        }
        return result;
    }

    public static HashMap<String, TrainInfo> parserTrainInfo(String response, String startDate) {
        HashMap<String, TrainInfo> result = new HashMap<String, TrainInfo>();
        String[] trainItems = response.replace("&nbsp;", "").split("\\\\n");
        for (int i = 0; i < trainItems.length; i++) {
            try {
                String[] items = trainItems[i].split(",");
                TrainInfo trainInfo = new TrainInfo();
                trainInfo.setStartDate(startDate);


                trainInfo.setSeq(items[0]);


                trainInfo.setTrainCode(extractInfo(items[1], "</span>"));   //T256
                trainInfo.setTrainNo(extractTrainNo(items[1])); // 6c0000G54802


                String[] tmpStrs = items[2].split("<br>");
                trainInfo.setFromStation(extractInfo(tmpStrs[0], ""));
                trainInfo.setSetoutTime(tmpStrs[1]);
                trainInfo.setFromStationImage(extractImageInfo(items[2]));

                tmpStrs = items[3].split("<br>");
                trainInfo.setToStation(extractInfo(tmpStrs[0], ""));
                trainInfo.setArriveTime(tmpStrs[1]);
                trainInfo.setToStationImage(extractImageInfo(items[3]));

                trainInfo.setPeriod(items[4]);

                trainInfo.setBuzSeat(extractInfo(items[5], "</font>"));
                trainInfo.setSpecialSeat(extractInfo(items[6], "</font>"));
                trainInfo.setFirstClassSeat(extractInfo(items[7], "</font>"));
                trainInfo.setSecondClassSeat(extractInfo(items[8], "</font>"));
                trainInfo.setAdvSoftSleeperSeat(extractInfo(items[9], "</font>"));
                trainInfo.setSoftSleeperSeat(extractInfo(items[10], "</font>"));
                trainInfo.setNormalSleeperSeat(extractInfo(items[11], "</font>"));
                trainInfo.setSoftSeat(extractInfo(items[12], "</font>"));
                trainInfo.setNormalSeat(extractInfo(items[13], "</font>"));
                trainInfo.setStandSeat(extractInfo(items[14], "</font>"));
                trainInfo.setOtherSeat(extractInfo(items[15], "</font>"));
                int index1 = items[16].indexOf("('") + 2;
                int index2 = items[16].indexOf("')");
                if (index2 == -1) {
                    index2 = index1;
                }
                trainInfo.setOtherInfo(items[16].substring(index1, index2));
                trainInfo.setMeta(trainInfo.getOtherInfo());
                trainInfo.setButtonInfo(extractButtonInfo(items[16]));
                result.put(trainInfo.getTrainCode(), trainInfo);
            } catch (Exception ex) {
//                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 把服务器返回的JSON数组对象转换成LIST对象。
     * @param json 服务器返回的JSON数组对象
     * @return 处理后的结果
     */
    public static List<List<String>> getTrainStopTimeData(String json) {
        List<List<String>> rows = new ArrayList<List<String>>();
        JSONArray array = null;
        try {
            array = new JSONArray(json);
        } catch (JSONException ex) {
            log.info(ex.getLocalizedMessage(), ex);
            return rows;
        }
        if (array == null) {
            return rows;
        }
        for (int i = 0; i < array.length(); i++) {
            org.json.JSONObject obj;
            try {
                obj = (org.json.JSONObject) array.get(i);
                List<String> row = new ArrayList<String>();
                row.add(obj.get("station_no").toString());
                row.add(obj.get("station_name").toString());
                row.add(obj.get("arrive_time").toString());
                row.add(obj.get("start_time").toString());
                row.add(obj.get("stopover_time").toString());
                row.add(obj.get("isEnabled").toString());
                rows.add(row);
            } catch (JSONException ex) {
                log.info(ex.getLocalizedMessage(), ex);
            }
        }
        return rows;
    }
}
